package cn.schoolwow.quickdao.module.database.ddl.query.service.index;

import cn.schoolwow.quickdao.domain.database.parent.DatabaseType;
import cn.schoolwow.quickdao.module.database.ddl.common.flow.SetHasResultSetFlow;
import cn.schoolwow.quickdao.module.database.parent.flow.executor.ExecuteQueryConnectionFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.Arrays;

public class HasConstraintFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        DatabaseType databaseType = flowContext.checkInstanceData(DatabaseType.class);
        String constraintName = (String) flowContext.checkData("constraintName");
        String tableName = (String) flowContext.checkData("tableName");

        switch (databaseType){
            case SQLite:{
                flowContext.putTemporaryData("sql", "select sql from sqlite_master where type='table'" +
                                " and name = ?" +
                                " and sql like '%foreign key%"+constraintName+"%';")
                        .putTemporaryData("parameters", Arrays.asList(tableName));
            }break;
            default:{
                flowContext.putTemporaryData("sql", "select constraint_name from information_schema.KEY_COLUMN_USAGE where constraint_name = ?;")
                        .putTemporaryData("parameters", Arrays.asList(constraintName));
            }break;
        }
        flowContext.startFlow(new SetHasResultSetFlow())
                .next(new ExecuteQueryConnectionFlow())
                .putTemporaryData("name", "判断约束是否存在")
                .execute();
    }

    @Override
    public String name() {
        return "约束是否存在";
    }
}
